package com.mswyt.utils.msThread;

import com.mswyt.utils.base.MsAopUtils;
import com.mswyt.utils.base.MsAssertUtils;
import com.mswyt.utils.msThread.annotation.MsAsync;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.concurrent.CompletionService;

/**
 * @ClassName: MsThreadAop
 * @Description:
 */
@Slf4j
@Aspect
@Component
public class MsThreadAop {

    private static final String NO_EXECUTOR_NAME = "线程池标识不可为空，请传入";

    /**
     * 切入点
     */
    @Pointcut("@annotation(com.mswyt.utils.msThread.annotation.MsAsync)) ")
    private void pointcut() {
    }

    @Around("pointcut()")
    public Object aroundAdvice(ProceedingJoinPoint joinPoint) throws Throwable {
        //获取方法上注解
        MsAsync msAsyncA = MsAopUtils.getAnnotation(joinPoint, MsAsync.class);
        String executorName = msAsyncA.executorName();
        MsAssertUtils.objIsNull(executorName, NO_EXECUTOR_NAME);
        //获取方法相关信息
        Method method = MsAopUtils.getMethod(joinPoint);
        Class<?> returnType = method.getReturnType();
        CompletionService<Object> completionService = MsThreadUtils.getCompletionService(executorName);
        //如果无返回值
        if (returnType.getName().equals("void")) {
            completionService.submit(() -> {
                try {
                    joinPoint.proceed();
                } catch (Throwable throwable) {
                    throwable.printStackTrace();
                }
            }, Thread.currentThread().getId() + "，执行：" + method.getClass().getName() + "." + method.getName());
        }
        return null;

    }
}
